#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include "cJSON.h"

void put_filename(int acceptfd, char buff[1024], int file_len);

int ftpServerInit(cJSON *data)
{
    printf("进入ftp服务器\n");
    char *flag = cJSON_GetObjectItem(data, "flag")->valuestring;
    char *file_name = cJSON_GetObjectItem(data, "file_name")->valuestring;
    int file_len = cJSON_GetObjectItem(data, "file_len")->valueint;
    int maxfd, ret;
    int acceptfd;
    int recvbyte;
    FILE *fp = NULL;
    char buf[1024] = {0};
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("sock err");
        return -1;
    }
    int yes = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
    {
        perror("setsockopt");
        // 错误处理
    }
    struct sockaddr_in saddr, caddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(8001);
    saddr.sin_addr.s_addr = INADDR_ANY;
    int len = sizeof(caddr);
    if (bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
    {
        perror("bind err");
        return -1;
    }
    if (listen(sockfd, 6) < 0)
    {
        perror("listen err");
        return -1;
    }
    acceptfd = accept(sockfd, (struct sockaddr *)&caddr, &len);
    if (acceptfd < 0)
    {
        perror("accept err");
        return -1;
    }
    char file_path[32];
    snprintf(file_path, sizeof(file_path), "/mnt/%s", file_name);
    printf("创建node.json文件\n");

    put_filename(acceptfd, file_path, file_len);
    printf("ftp server exit\n");
    return 0;
}

void put_filename(int acceptfd, char filename[128], int file_len)
{
    printf("put_filename\n");
    char buf[1024] = {0};  
    int recvbyte;  
    int total_received = 0; // 用来跟踪已经接收的字节数  
    FILE *fp = fopen(filename, "wb"); // 使用"wb"模式以二进制方式写入  
    if (fp == NULL)  
    {  
        perror("fopen err");  
        return;  
    }  
    while (total_received < file_len) // 循环直到接收了足够的字节  
    {  
        int bytes_to_receive = file_len - total_received;
        if (bytes_to_receive > sizeof(buf) - 1)
            bytes_to_receive = sizeof(buf) - 1; 
  
        recvbyte = recv(acceptfd, buf, bytes_to_receive, 0); // 接收数据  
        if (recvbyte <= 0)  
        {  
            if (recvbyte < 0)  
                perror("recv err");  
            break;  
        }  
  
        // 写入到文件  
        fwrite(buf, 1, recvbyte, fp);  
        total_received += recvbyte;
    }  
    printf("接收结束\n");
    if (fp)  
        fclose(fp); 
    return;
}